import React, { useRef, useState, useEffect } from 'react';
import { View, Image, Text, Picker,Textarea } from '@tarojs/components';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import {AtIcon , AtActionSheet} from 'taro-ui'
import OrderCancleReason from '../activityCancleReason/index';
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/action-sheet.scss";
import './index.scss';
import QRCode from '@/utils/weapp-qrcode.js'
import {
  commentUploadImgServer
} from '@/services/comment';

const ActivityDetaili = ({ dispatch }) => {
  const limitCount = 9
  const [info,setInfo] = useState({})
  const id = useRef('')
  const [curData,setCurData] = useState({})
  const [showModal,setShowModal] = useState(false)
  const [showCode,setShowCode] = useState(false)
  const [showUpload,setShowUpload] = useState(false)
  const [showPrice,setShowPrice] = useState(false)
  const [showExpire,setShowExpire] = useState(false)
  const [showInfo,setShowInfo] = useState(false)
  const [codeImg,setCodeImg] = useState('')
  const [uploadMap, setUploadMap] = useState({});
  const [config,setConfig] = useState({})
  
  useEffect(()=>{
    id.current = getCurrentInstance().router.params.orderId
    _initData(getCurrentInstance().router.params.orderId)
  },[])
  const [isOpened, setIsOpened] = useState(false);
  const handleSelected = (reasonStatus,data) => {
    setUploadMap({...uploadMap,
      reason:reasonStatus,
      reasonName:data.value
    })
    setIsOpened(false);
  };

  const [state, updateState] = useState({
    files: [],
  });
  const setState = (val) => {
    const res = { ...state, ...val };
    updateState(res);
  };
  //选择图片
  const handleChooseImage = () => {
    Taro.chooseImage({
      count: 9 - state.files.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        if (state.files.length + res.tempFilePaths.length > limitCount) {
          Taro.showToast({
            title: `最多上传${limitCount}张图片`,
            duration: 1000,
            icon: 'none',
          });
        } else {
          setState({ files: state.files.concat(res.tempFilePaths) });
        }
      },
    });
  };
  //删除图片
  const handleDelImg = (idx) => {
    //因渲染机制增加定时器
    setTimeout(() => {
      state.files.splice(idx, 1);
      setState({
        files: state.files,
      });
    }, 0);
  };
  const handleSubmit = e=>{ /// 提交数据
    const data = {
      "cerImageUrl": uploadMap.files,
      "description": uploadMap.description,
      "orderId": info.orderId,
      "reason": uploadMap.reason
    }
    if(!data.reason){
      Taro.showToast({
        title:'请先选择退款原因',
        icon:'none'
      })
      return;
    }
    Taro.$post(`/order/after-sales/commit`,data).then(res=>{
      if(res.code == '1'){
        Taro.showToast({
          title:'提交成功',
          icon:'success'
        })
        setShowModal(false)
        setTimeout(() => {
          _initData(data.orderId)
        }, 1000);
      }else{
        Taro.showToast({
          title:res.message,
          icon:'none'
        })
      }
    })
  }
  const updateTimeData = e=>{
    const timeData = {}
    const time = info.processingTime*1000 || 0
    if(time){
      timeData.day = Math.floor(time / 1000 / 60 / 60 / 24);
      timeData.hour = Math.floor((time / 1000 / 60 / 60) % 24);
      timeData.minute = Math.floor((time / 1000 / 60) % 60);
      timeData.second = Math.floor((time / 1000) % 60);
    }
    return timeData
  }
  const _initData =e=>{
    Taro.$get(`/store/v1/orders/detail?orderId=${e}`).then(res=>{
      if(res.code == '1') setInfo(res.content)
    })
  }
  return (
  <View className="goods-detail">
    {info.orderId?<>
    <View className='detail-status'>
      {info.businessStatusDesc?.includes('退款')?<>
        <Text className='at-icon at-icon-check-circle' style={{marginRight:'6px',fontSize:'20px'}}></Text> {info.businessStatusDesc}
        <View className="status-span">{info.processingTimeDesc}</View>
        <View className="status-price"><Text style={{fontSize:'10px'}}>￥</Text>{info.totalPayment}</View>
        <View className="status-p">
          {info.afterSaleTime} <br /> {info.businessStatus == '3' || info.businessStatus == '5'?'商家已退款，钱款已原路退回。':'商家已收到您的退款申请，正在等待商家审核。'}
        </View>
      </>:<>
        <Text className='at-icon at-icon-check-circle' style={{marginRight:'6px',fontSize:'20px'}}></Text> {info.businessStatusDesc}
        {info.businessStatus == '1'?<>
        <View className="status-article">在影院卖品柜台出示取餐码，领取已购买的卖品。</View>
        <View className="status-button" onClick={()=>{
          setCodeImg(QRCode.drawImg(info.qrCode, {
            size: 320
          }))
          setShowCode(true)
        }}>取餐码</View>
        </>:null}
        {info.businessStatus == '2'?<>
        <View className="status-article">在影院卖品柜台出示取餐码，领取已购买的卖品。</View>
        <View className="status-button disabled">已核销</View>
        </>:null}
      </>}
    </View>
    {showCode?
    <View className="detail-code" onClick={()=>{setShowCode(false)}}>
      <View className="code-main">
        <Image src={codeImg} mode='widthFix' style={{width:'200px'}} />
      </View>
    </View>:null}
    <View className="detail-header">
      {info.orderItemInfos?.map((res,idx)=>{
        return <View className="header-list" key={idx}>
          <Image src={res.mainImageUrl} className='header-img' />
          <View className="header-info">
            <View className="info-h2 omit-2">{res.title}</View>
            <View className="info-p">x {res.quantity}</View>
          </View>
          <View className="header-price">
            {res.totalPayment?<View className="price-h2">实付<Text style={{fontSize:'10px'}}>￥</Text>{res.totalPayment}</View>:null}
            {/* <View style={{textAlign:'right',textDecoration:'line-through'}}>￥{res.totalPrice}</View> */}
          </View>
        </View>
      })}
      <View className="header-span">
        <View className="span-price"><Text style={{fontSize:'12px'}}>实付款</Text><Text style={{fontSize:'10px'}}>￥</Text>{info.totalPayment}</View>
        <Text onClick={()=>{setShowPrice(!showPrice)}} className={`at-icon at-icon-chevron-${showPrice?'up':'down'}`}></Text>
      </View>
      {showPrice?
      <View className="detail-price">
        <View className="price-list">
          <View className="p">订单总价</View>
          <Text style={{fontSize:'10px'}}>￥</Text>{info.totalPrice}
        </View>
        <View className="price-list">
          <View className="p">优惠</View>
          <View style={{color:'#f73'}}>减 <Text style={{fontSize:'10px'}}>￥</Text>{info.totalDiscount || 0}</View>
        </View>
        <View className="price-list">
          <View className="p">运费</View>
          <Text style={{fontSize:'10px'}}>￥</Text>0.00
        </View>
        <hr style={{height:'1px',border:'none',borderTop:'1px solid #EEEEEF',marginBottom:'12px'}} />
        <View className="price-list">
          <View className="p">订单实付</View>
          <Text style={{fontSize:'10px'}}>￥</Text>{info.totalPayment}
        </View>
      </View>:null}
    </View>
    <View className="detail-intro">
      <View className="intro-shop">
        <Image className='shop-img' src={info.sellerUserAvatar} />
        {info.sellerUserName}
      </View>
      <View className="intro-list"><View className='p'>订单编号</View> {info.orderId} <Text className='span' style={{color: '#90989F',margin: '0 6px'}}>|</Text> <Text className='span' onClick={()=>{
        Taro.setClipboardData({
          data:info.orderId,
          success: () => {
            Taro.showToast({
              title:'复制成功',
              icon:'success'
            })
          }
        })}}>复制</Text></View>
      {showInfo?<>
        {info.transId?
        <View className="intro-list">
          <View className='p'>支付流水号</View> 
          {info.transId}
        </View>:null}
        <View className="intro-list">
          <View className='p'>创建时间</View> 
          {info.created}
        </View>
        {info.paymentTime?
        <View className="intro-list">
          <View className='p'>付款时间</View>
          {info.paymentTime}
        </View>:null}
        {info.finishTime?
        <View className="intro-list">
          <View className='p'>完成时间</View>
          {info.finishTime}
        </View>:null}
      </>:null}
      <View className="intro-list">
        <View className='p'>更多信息</View>
        <Text style={{color:'#90989F'}} onClick={()=>{setShowInfo(!showInfo)}}>{showInfo?'收起':'展开'}</Text> <Text className={`at-icon at-icon-chevron-${showInfo?'up':'down'}`}></Text>
      </View>
    </View>

    {info.canRefundOrder?
    <View className="detail-button">
      <View className="button-item" onClick={()=>{
        Taro.$get('/order/users/orders/checkAfterSale',{orderId:getCurrentInstance().router.params.orderId}).then(res=>{
          if(res.code == '1'){
            setShowModal(true)
          }else{
            setShowExpire(true)
          }
        })
      }}>申请售后</View>
    </View>:null}
    
    <OrderCancleReason
      isOpened={isOpened}
      handleClose={()=>{setIsOpened(false)}}
      handleSelected={handleSelected}
      key={id.current}
      source={info.orderSource}
    />
    <AtActionSheet isOpened={showExpire} onClose={()=>{setShowExpire(false)}}>
      <View className="expire-modal">
        <Image className='modal-img' src={require('@/static/Illustration.png')} />
        <View className="modal-h1">抱歉，订单已过售后申请时效</View>
        <View>如您对商品售后有疑问，可联系客服处理</View>
        <View className="modal-button" onClick={()=>{
          setShowExpire(false)
        }}>返回</View>
      </View>
    </AtActionSheet>
    <AtActionSheet isOpened={showModal} onClose={()=>{setShowModal(false)}}>
      <View className="activity-popup">
        <View className="popup-header">
          <View></View><View className="header-h2">确认退款信息</View>
          <AtIcon value='close' size='16' color='#000' onClick={()=>{setShowModal(false)}}></AtIcon>
        </View>
        <View className="popup-main">
          {info.orderItemInfos?.map((res,idx)=>{
            return <View className="main-item" key={idx}>
            <Image className="main-img" src={res.mainImageUrl} />
            <View className="main-info">
              <View className="h2 omit-2">{res.title}</View>
              <View className="p">x {res.quantity}</View>
            </View>
            <View className="main-price">
              <View className="price-h2">实付<Text style={{fontSize:'10px'}}>￥</Text>{res.totalPrice}</View>
              {/* <View style={{textAlign:'right',textDecoration:'line-through'}}>￥90.00</View> */}
            </View>
          </View>
          })}
        </View>
        <View className="popup-list">
          <View className="main-list">
              <View className="list-p">退款原因</View>
              <Text style={{color:'#90989F'}} onClick={()=>{setIsOpened(true)}}>{uploadMap.reasonName || '请选择退款原因'} <AtIcon value='chevron-right' size='16' color='#90989F'></AtIcon></Text>
            </View>
            <View className="main-list">
              <View className="list-p">退款金额</View>
              <Text>￥</Text>{info.totalPayment}
            </View>
            <View className="main-list">
              <View className="list-p">上传描述和凭证</View>
              {uploadMap?.files?.length || uploadMap?.description?<Text>
                {uploadMap?.files?.length?' 凭证':null}
                {uploadMap?.description?' 描述':null} 
                <AtIcon value='chevron-right' size='16' color='#90989F'></AtIcon>
              </Text>:
              <Text style={{color:'#90989F'}} onClick={()=>{setShowUpload(true)}}>上传有助于处理问题 <AtIcon value='chevron-right' size='16' color='#90989F'></AtIcon></Text>}
            </View>
        </View>
        <View className="popup-footer">
          <View className="footer-info"><Text style={{fontWeight:'500',color:'#30383F',marginRight:'8px'}}>退款总金额</Text> <Text style={{fontSize:'10px'}}>￥</Text>{info.totalPayment}</View>
          <View className="footer-button" onClick={()=>{handleSubmit()}}>提交申请</View>
        </View>
      </View>
    </AtActionSheet>
    <AtActionSheet isOpened={showUpload} onClose={()=>{setShowUpload(false)}}>
      <View className="activity-popup">
        <View className="popup-header">
          <View></View><View className="header-h2">上传描述和凭证</View>
          <AtIcon value='close' size='16' color='#000' onClick={()=>{setShowUpload(false)}}></AtIcon>
        </View>
        <View className="popup-main">
          <Textarea style={{height:'100px',width:'100%'}} maxlength={200} placeholder='补充描述,有助于商家更好的处理售后问题' onInput={e=>{
            setState({...state,description:e.detail.value})
          }}></Textarea>
          <View className="main-imgs">
            {state.files.length < 9?
            <View className="imgs-button" onClick={()=>{handleChooseImage()}}>
              上传凭证<br />(最多9张)
            </View>:null}
            {state.files.map((box,idx)=>(
              <View className="imgs-item" key={idx}>
                <Image src={box} mode='aspectFill' className='item-img' />
                <Image src={require('@/static/close.png')} onClick={()=>{handleDelImg(idx)}} className='item-icon' />
            </View>
            ))}
          </View>
        </View>
        <View className="popup-footer" style={{marginTop:'10px'}}>
          <View className="footer-button" style={{borderRadius:'40px'}} onClick={async ()=>{
            let imgs = {};
            let files = uploadMap.files || []
            const imgUrls = state.files || [];
            for (let file of imgUrls) {
              if (!!uploadMap[file]) {
                //避免重复上传
                imgs[file] = uploadMap[file];
                continue;
              }
              const fileRes = await commentUploadImgServer(file);
              if (fileRes.code == 1 && fileRes.content) {
                imgs[file] = fileRes.content;
                files.push(fileRes.content)
              }else{
                Taro.showToast({
                  title:'上传失败',
                  icon:'none'
                })
                return;
              }
            }
            setUploadMap({
              ...uploadMap,
              ...imgs,
              files,
              description:state.description
            });
            setShowUpload(false)
          }}>完成</View>
        </View>
      </View>
    </AtActionSheet>
    </>:null}
  </View>
  );
};

export default ActivityDetaili
